package controllers

import config.{MyAwait, Search}
import javax.inject.Inject
import play.api.libs.json.Json
import play.api.mvc.{AbstractController, ControllerComponents}
import utils.TableUtils.pageForm

import scala.concurrent.ExecutionContext

class AllSearchController @Inject()( cc: ControllerComponents)
                                   (implicit exec: ExecutionContext) extends AbstractController(cc) with MyAwait{

  def searchPage(input:String) = Action{implicit request=>
    Ok(views.html.allSearch.searchPage(input))
  }

  def searchByDbInput(input: String) = Action { implicit request =>
    val page = pageForm.bindFromRequest.get
    val option = Array("Gene ID" , "NR tophit name", "Swiss tophit name","COG/KOG", "GO", "KO", "Pfam ID")

    if (Search.searchMap.getOrElse(input, "") == "") {
      Search.getSearchMap(input)
    }

    Search.searchTimeMap.put(input, System.currentTimeMillis())

    val result = Search.searchMap(input)

    val total = result.size
    val tmpX = result.slice(page.offset, page.offset + page.limit)

    val keys = input.trim.split(" ").map(_.trim)
    val row = tmpX.map { x =>
      val r = Search.search.find(_._1 == x._2).get
      val species = r._2

      val text = r._3.split("\t")
      val result = keys.map { k =>
        val results = text.zipWithIndex.find(_._1.toLowerCase.indexOf(k.toLowerCase) != -1).get
        val r =  Search.getKeyWord(results._1, input)

        Json.obj("option" -> option(results._2), "result" ->r)
      }.distinct


      val s = species match{
        case  "CON" => "Camellia oleifera  Abel. var. “Nanyongensis”"
        case "Camellia_lanceoleosa" =>  "Camellia lanceoleosa"
        case "Coleifera"=>  "Camellia chekiangoleosa "
      }

      Json.obj("id" -> r._1, "geneid" -> text.head, "species" -> s,"speciesId" -> x._1,
        "result" -> result)
    }

    Ok(Json.obj("rows" -> row, "total" -> total))
  }


}
